Socket网络通讯主机,物联网通讯,和控制机器设备实现通讯
using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.IO.Ports;using System.Text;using System.Windows.Forms;using UtilityProject;namespace PortControlDemo{ public partial class MainHot : Form { /// <summary> /// 创建串口对象 /// </summary> private SerialPort port = new SerialPort(); /// <summary> /// 接受消息 /// </summary> private StringBuilder MsgStr = new StringBuilder(); /// <summary> /// 构造函数 /// </summary> public MainHot() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; //防止跨线程访问出错,好多地方会用到 } private void setopen_Click(object sender, EventArgs e) { } private void setclose_Click(object sender, EventArgs e) { //关 // pchSend.SendData(tb_send.Text); } private void setdw_Click(object sender, EventArgs e) { //档位 if (seldw.SelectedIndex >= 0) { string strdw = "0" (seldw.SelectedIndex 1).ToString(); // MessageBox.Show(strdw); //pchSend.SendData(tb_send.Text); } else { MessageBox.Show("请先选择要设置阀门的档位"); } } private void MainHot_Load(object sender, EventArgs e) { cbtsdz.SelectedIndex = 0; // setclose.Enabled = false; setopen.Enabled = false; setdw.Enabled = false; seldw.Enabled = false; view.Enabled = false; btnsetkzid.Enabled = false; btngetkzid.Enabled = false; btnsetjzqid.Enabled = false; btngetjzqid.Enabled = false; btnsetid.Enabled = false; btnsetip.Enabled = false; btnsetdk.Enabled = false; btnsetsn.Enabled = false; btngetinfo.Enabled = false; // clsglx.SelectedIndex = 0; clfmlx.SelectedIndex = 0; // ///获取窗口列表 string[] ports = SerialPort.GetPortNames(); if (ports.Length > 0) { ///添加可选通讯口 com.Items.AddRange(ports); ///设置默认选择 com.SelectedIndex = 0; bot.SelectedIndex = 0; databit.SelectedIndex = 0; stopbit.SelectedIndex = 0; jy.SelectedIndex = 0; } else { MessageBox.Show("没有可用的串口!"); } } private void setclose_Click_1(object sender, EventArgs e) { } private void comboBox6_SelectedIndexChanged(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { try { ///检测串口是否开着 if (!port.IsOpen) { ///设置串口名称 port.PortName = com.SelectedItem.ToString(); ///设置波特率 port.BaudRate = Convert.ToInt32(bot.Text); ///数据位 port.DataBits = Convert.ToInt32(databit.Text); ///设置无协议 port.Handshake = Handshake.None; ///设置读取不超时 port.ReadTimeout = -1; //port.WriteTimeout = -1; ///设置停止位 port.StopBits = GetStopBits(stopbit.SelectedIndex 1); port.DtrEnable = true; ///无校验 port.Parity = GetParity(jy.SelectedIndex); ///设置数据接收事件 // port.DataReceived = ReciveData; port.DataReceived = Port_DataReceived; ///打开串口 port.Open(); open.Text = "关闭串口"; UpdateStutas(); setclose.Enabled = true; setopen.Enabled = true; setdw.Enabled = true; seldw.Enabled = true; view.Enabled = true; btnsetkzid.Enabled = true; btngetkzid.Enabled = true; btnsetjzqid.Enabled = true; btngetjzqid.Enabled = true; btnsetid.Enabled = true; btnsetip.Enabled = true; btnsetdk.Enabled = true; btnsetsn.Enabled = true; btngetinfo.Enabled = true; } else { ///关闭串口 port.Close(); // port.DataReceived -= ReciveData; port.DataReceived -= Port_DataReceived; open.Text = "打开串口"; setclose.Enabled = false; setopen.Enabled = false; setdw.Enabled = false; seldw.Enabled = false; view.Enabled = false; btnsetkzid.Enabled = false; btngetkzid.Enabled = false; btnsetjzqid.Enabled = false; btngetjzqid.Enabled = false; btnsetid.Enabled = false; btnsetip.Enabled = false; btnsetdk.Enabled = false; btnsetsn.Enabled = false; btngetinfo.Enabled = false; } } catch (Exception ex) { MessageBox.Show("端口设置错误!"); } finally { UpdateStutas(); } } private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (rbshowasc.Checked)//判断是否选中了字符选项 { string str = port.ReadExisting();//保存接收到的字符 txtdata.AppendText(str);//显示出接收到的字符 } else if (rbshowhex.Checked)//数值模式 { byte data; data = (byte)port.ReadByte();//读取串口接收的一个字节 string str = Convert.ToString(data, 16).ToUpper();//将读取到的字节转换成十六进制字符串显示 txtdata.AppendText("0x" (str.Length == 1 ? "0" str : str) " ");//在文本框中显示出转换后的字符串 } } /// <summary> /// 数据接收事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ReciveData(object sender, SerialDataReceivedEventArgs e) { lbview.Text = ""; txtdata.Text = ""; ///是否接受完整 bool isStop = false; ///数据长度 int count = port.BytesToRead; string msg = null; //{ byte[] buff = new byte[count]; ///接收数据 port.Read(buff, 0, count); ///将比特数据转换为字符串 foreach (byte buf in buff) { try { if (rbshowasc.Checked) { // msg = System.Text.Encoding.ASCII.GetBytes(); // msg = Convert.ToString(buff); msg = AddData(buff); } else if (rbshowhex.Checked) { msg = Convert.ToString(buf, 16); } if (msg.Length == 1) { msg = "0" msg; } //if (msg == "16") //{ isStop = true; //} MsgStr.Append(msg " "); } catch (Exception) { MessageBox.Show("设备返回不支持的数据!"); } } if (!isStop) { return; } ///显示数据 //data.Text = "-----------查询返回状态信息:-----------------\n"; //data.Text = DateTime.Now.ToString() ":---->" MsgStr '\n'; //data.Text = "----------------------------\n"; txtdata.Text = MsgStr; ///分割接收的消息 string[] revbuff = MsgStr.ToString().Trim().Split(' '); // MessageBox.Show(revbuff[20] "__" revbuff[19] "__" revbuff[18]); //FE FE 68 10 AA AA AA AA AA AA AA 81 08 1F 90 00 01 2D 01 3d 01 1d 16 // lbview.Text = "阀门位置:" revbuff[17] " " ";当前温度:" revbuff[19] "." revbuff[18] "摄氏度"; MsgStr.Clear(); //刷新 } /// <summary> /// 解码过程 /// </summary> /// <param name="data">串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取</param> private string AddData(byte[] data) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i ) { sb.AppendFormat("{0:x2}" " ", data[i]); } return sb.ToString();// } private void send_Click(object sender, EventArgs e) { if(message.Text.Trim().Length<1) { MessageBox.Show("请输入发送数据信息!"); return; } if (rbasc.Checked) { SendMsg2(message.Text, 1); } else if(rbhex.Checked) { SendMsg2(message.Text, 0); } else { MessageBox.Show("请选择发送数据类型!"); } } /// <summary> /// 获取串口状态 /// </summary> /// <returns></returns> private void UpdateStutas() { if (!port.IsOpen) return; string stuta = port.PortName ": " port.IsOpen.ToString() " DSR:" port.DsrHolding " CDH:" port.CDHolding " CTS:" port.CtsHolding; // stutas.Text = stuta; } /// <summary> /// 发信 /// </summary> /// <param name="newmsg"></param> /// <param name="dttype">发送数据格式,0:16进制 1:ASCII码</param> private void SendMsg2(string newmsg, int dttype) { newmsg = newmsg "\r\n"; if (!port.IsOpen) { MessageBox.Show("端口已被关闭!"); return; } // UpdateStutas(); ///清理残余的缓冲区 port.DiscardInBuffer(); port.DiscardOutBuffer(); //转换列表为数组后发送 if (dttype == 0) { ///分割要发送的消息 string[] sendbuff = newmsg.Split(' '); ///发送数据 List<byte> buf = new List<byte>();//填充到这个临时列表中 foreach (string msg in sendbuff) { try { buf.Add(byte.Parse(msg, System.Globalization.NumberStyles.HexNumber)); // buf.Add(byte.Parse(msg)); } catch (Exception ex) { MessageBox.Show(ex.Message "._" msg "不是有效的十六进制数字"); return; } } port.Write(buf.ToArray(), 0, buf.Count); } else if(dttype==1) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(newmsg); port.Write(bytes, 0, bytes.Length);//发送数据 } //记录发送的字节数 // sendnum.Text = "发送字节数:" buf.Count; } private void SendMsg(string newmsg) { if (!port.IsOpen) { MessageBox.Show("端口已被关闭!"); return; } // UpdateStutas(); ///清理残余的缓冲区 port.DiscardInBuffer(); port.DiscardOutBuffer(); //转换列表为数组后发送 ///分割要发送的消息 string[] sendbuff = newmsg.Split(' '); ///发送数据 List<byte> buf = new List<byte>();//填充到这个临时列表中 foreach (string msg in sendbuff) { try { buf.Add(byte.Parse(msg, System.Globalization.NumberStyles.HexNumber)); // buf.Add(byte.Parse(msg)); } catch (Exception ex) { MessageBox.Show(ex.Message "._" msg "不是有效的十六进制数字"); return; } } port.Write(buf.ToArray(), 0, buf.Count); // byte[] bytes = System.Text.Encoding.ASCII.GetBytes(newmsg); // port.Write(bytes, 0, bytes.Length);//发送数据 //记录发送的字节数 // sendnum.Text = "发送字节数:" buf.Count; } /// <summary> /// 获取停止位 /// </summary> /// <param name="num"></param> /// <returns></returns> private StopBits GetStopBits(int num) { foreach (StopBits bit in Enum.GetValues(typeof(StopBits))) { if ((int)bit == num) { return bit; } } return StopBits.None; } /// <summary> /// 获取校验 /// </summary> /// <param name="num"></param> /// <returns></returns> private Parity GetParity(int num) { foreach (Parity bit in Enum.GetValues(typeof(Parity))) { if ((int)bit == num) { return bit; } } return Parity.None; } private string[] idsplits(string source,int count) { List<string> list = new List<string>(); string temp = string.Empty; if (source.Length % count != 0) source = source.PadRight(source.Length (count - source.Length % count)); for (int i = 0; i < source.Length; i = i count) { for (int j = 0; j < count; j ) { temp = source[i j]; } list.Add(temp); temp = string.Empty; } return list.ToArray(); } private void message_TextChanged(object sender, EventArgs e) { } private void btnsetjzqid_Click(object sender, EventArgs e) { //得到集中器编号的值 string str = txtjzqID.Text.Trim(); if (str.Length == 7) { string strmsg = "SET CPU ID " str; SendMsg2(strmsg, 1); } else { MessageBox.Show("请正确输入设备编号!"); } } /// <summary> /// 写入控制器地址编号 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnsetkzid_Click_1(object sender, EventArgs e) { txtdata.Text = ""; string strfmlx = ""; string strsglx = ""; try { if (clfmlx.SelectedIndex < 1) { MessageBox.Show("请正确选择阀门类型!!"); return; } else if (clfmlx.SelectedIndex == 1) { strfmlx = "0"; } else if (clfmlx.SelectedIndex == 2) { strfmlx = "5"; } if (clsglx.SelectedIndex < 1) { MessageBox.Show("请正确选择水管类型!!"); return; } strsglx = clsglx.SelectedItem.ToString(); // 获取最新地址值 test by wed 2019-10-28 // string str = txtkzfid.Text.Trim(); string connstr = SimpleSqlHelper.GetConnString(); string sql = "select top 1 * from kzqproducts where scnd =DATEPART(year,getdate()) order by id desc"; DataSet dsbh = SimpleSqlHelper.ExecuteDataset(connstr, CommandType.Text, sql); txtnewcpid.Text = dsbh.Tables[0].Rows[0]["cpbh"].ToString(); txtnewkzqid.Text = dsbh.Tables[0].Rows[0]["kzqbh"].ToString(); int bhxh = Convert.ToInt32(txtnewcpid.Text) 1; txtcpbh.Text = bhxh.ToString(); int dzxh = Convert.ToInt32(txtnewkzqid.Text.Substring(7)) 1; txtkzfid.Text = strfmlx strsglx txtcpbh.Text.Substring(0, 2).ToString() cbtsdz.SelectedItem.ToString() dzxh.ToString().PadLeft(7, '0'); //end test } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } string str = txtkzfid.Text.Trim(); if (str.Length == 14) { str = "6811" str; string idw = string.Empty; // "37 82 00 00 00 00 01 "; string jyhw = "00"; //D1 string[] idstrs = idsplits(str, 2); //3组到20组累加取余,结果给21组 UInt64 sn = 0; for (int k = 0; k < idstrs.Length; k ) { sn = sn Convert.ToUInt64(idstrs[k], 16); } int m = Convert.ToInt32(sn); jyhw = Convert.ToString(m, 16); if (jyhw.Length > 2) { jyhw = jyhw.Substring(1); } else if (jyhw.Length < 2) { jyhw = "0" jyhw; } idw = string.Join(" ", idstrs); string strmsg = "FE FE FE FE " idw " " jyhw " 16"; txtzl.Text = strmsg; SendMsg2(strmsg, 0); //写入地址成功返回后记录库 string strpro = "p_addinfo"; SqlParameter[] ps ={ new SqlParameter("@cpbh",txtcpbh.Text), new SqlParameter("@kzqbh",txtkzfid.Text), new SqlParameter("@fmlx",strfmlx), new SqlParameter("@sglx",strsglx), new SqlParameter("@cjr","user0") }; string connstr = SimpleSqlHelper.GetConnString(); SimpleSqlHelper.ExecuteNonQuery(connstr, CommandType.StoredProcedure, strpro, ps); } else { MessageBox.Show("请先生成正确的14位数字控制阀编号!!"); } } private void view_Click_1(object sender, EventArgs e) { if (txtid.Text.Trim().Length > 0) { ////得到选中行的索引 //int intRow = dg1.SelectedCells[0].RowIndex; ////得到列的索引 //int intColumn = dg1.SelectedCells[0].ColumnIndex; //得到选中行某列的值 string str = txtid.Text.Trim(); // MessageBox.Show(str); if (str.Length >= 14) { string strmsg = "FE FE FE FE 68 10 " str " 01 03 1F 90 00 D1 16"; lbview.Text = ""; txtdata.Text = ""; SendMsg(strmsg); } else { MessageBox.Show("请点击列表选择框正确选择一条设备记录!"); } } else { MessageBox.Show("请点击列表选择框选择一条设备记录!"); } } private void btngetkzid_Click_1(object sender, EventArgs e) { //test by wed 2019-10-28 string str = txtkzfid.Text.Trim(); string connstr = SimpleSqlHelper.GetConnString(); // string sql = "select * from Hot_Tdqxxs where wkqbh = '" str "'"; // DataSet dsCamera = SimpleSqlHelper.ExecuteDataset(connstr, CommandType.Text, sql); //end test } private void setopen_Click_1(object sender, EventArgs e) { //开 // pchSend.SendData(tb_send.Text); //string strmsg = "FE FE FE 68 10 AA AA AA AA AA AA AA 04 06 17 A0 00 05 65 78 11 16"; //SendMsg(strmsg); if (txtid.Text.Trim().Length > 0) { ////得到选中行的索引 //int intRow = dg1.SelectedCells[0].RowIndex; ////得到列的索引 //int intColumn = dg1.SelectedCells[0].ColumnIndex; //得到选中行某列的值 string str = txtid.Text.Trim(); // MessageBox.Show(str); if (str.Length >= 14) { string strmsg = "FE FE FE 68 10 " str " 04 06 17 A0 00 05 65 78 11 16"; SendMsg(strmsg); } else { MessageBox.Show("请点击列表选择框正确选择一条设备记录!"); } } else { MessageBox.Show("请点击列表选择框选择一条设备记录!"); } } private void setdw_Click_2(object sender, EventArgs e) { //if (seldw.SelectedIndex >= 0) //{ // string strmsg = "FE FE FE 68 10 AA AA AA AA AA AA AA 04 06 17 A0 00 " seldw.SelectedItem.ToString() " 65 78 11 16"; // SendMsg(strmsg); //} //档位 if (txtid.Text.Trim().Length > 0) { //得到选中行某列的值 string str = txtid.Text.Trim(); // MessageBox.Show(str); if (str.Length >= 14) { if (seldw.SelectedIndex >= 0) { string strmsg = "FE FE FE 68 10 " str " 04 06 17 A0 00 " seldw.SelectedItem.ToString() " 65 78 11 16"; SendMsg(strmsg); } } else { MessageBox.Show("请点击列表选择框正确选择一条设备记录!"); } } else { MessageBox.Show("请点击列表选择框选择一条设备记录!"); } } private void setclose_Click_2(object sender, EventArgs e) { // string strmsg = "FE FE FE 68 10 AA AA AA AA AA AA AA 04 06 17 A0 00 00 65 78 11 16"; // SendMsg(strmsg); //关 if (txtid.Text.Trim().Length > 0) { ////得到选中行的索引 //int intRow = dg1.SelectedCells[0].RowIndex; ////得到列的索引 //int intColumn = dg1.SelectedCells[0].ColumnIndex; //得到选中行某列的值 string str = txtid.Text.Trim(); // MessageBox.Show(str); if (str.Length >= 14) { string strmsg = "FE FE FE 68 10 " str " 04 06 17 A0 00 00 65 78 11 16"; SendMsg(strmsg); } else { MessageBox.Show("请点击列表选择框正确选择一条设备记录!"); } } else { MessageBox.Show("请点击列表选择框选择一条设备记录!"); } } private void btngetjzqid_Click(object sender, EventArgs e) { //获取串口连接集中器的编号 string strmsg = "GET ID"; SendMsg2(strmsg, 1); } private void button2_Click(object sender, EventArgs e) { } //获取到最新的控制器地址编号序号 private void button3_Click_1(object sender, EventArgs e) { try { string strfmlx = ""; if (clfmlx.SelectedIndex < 1) { MessageBox.Show("请正确选择阀门类型!!"); return; } else if (clfmlx.SelectedIndex == 1) { strfmlx = "0"; } else if (clfmlx.SelectedIndex == 2) { strfmlx = "5"; } if (clsglx.SelectedIndex < 1) { MessageBox.Show("请正确选择水管类型!!"); return; } string strsglx = clsglx.SelectedItem.ToString(); // 获取最新地址值 test by wed 2019-10-28 // string str = txtkzfid.Text.Trim(); string connstr = SimpleSqlHelper.GetConnString(); string sql = "select top 1 * from kzqproducts where scnd =DATEPART(year,getdate()) order by id desc"; DataSet dsbh = SimpleSqlHelper.ExecuteDataset(connstr, CommandType.Text, sql); txtnewcpid.Text = dsbh.Tables[0].Rows[0]["cpbh"].ToString(); txtnewkzqid.Text = dsbh.Tables[0].Rows[0]["kzqbh"].ToString(); int bhxh = Convert.ToInt32(txtnewcpid.Text) 1; txtcpbh.Text = bhxh.ToString(); int dzxh = Convert.ToInt32(txtnewkzqid.Text.Substring(7)) 1; txtkzfid.Text = strfmlx strsglx txtcpbh.Text.Substring(0, 2).ToString() cbtsdz.SelectedItem.ToString() dzxh.ToString().PadLeft(7, '0'); //end test txtsetid.Text = txtkzfid.Text; //生成地址显示 } catch(Exception ex) { MessageBox.Show(ex.Message.ToString()); } } private void btngetjzq_Click(object sender, EventArgs e) { //获取到最新的集中器编号序号 string connstr = SimpleSqlHelper.GetConnString(); string jzqsql = "SELECT * FROM [dbo].[kzlinks] where scnd = DATEPART(year,getdate()) and scyf = DATEPART(month,getdate()) order by id desc"; DataSet dsjzqbh = SimpleSqlHelper.ExecuteDataset(connstr, CommandType.Text, jzqsql); lbjzqbh.Text = dsjzqbh.Tables[0].Rows[0]["jzqbh"].ToString(); int bh = Convert.ToInt32(lbjzqbh.Text) 1; txtjzqID.Text = bh.ToString(); //end test 2019-11-04 } private void btnsetip_Click(object sender, EventArgs e) { //设置主机连接IP string strmsg = "SET SERVER IP ";//047.104.137.177 strmsg = strmsg txtip.Text.Trim(); SendMsg2(strmsg, 1); } private void btnsetsn_Click(object sender, EventArgs e) { //设置心跳时间间隔8秒 string strmsg = "SET BETA TIME GAP ";//300 strmsg = strmsg txtsjjg.Text.Trim(); // strmsg = strmsg "\r\n"; SendMsg2(strmsg, 1); } private void btngetinfo_Click(object sender, EventArgs e) { txtdata.Text = ""; //查看现有配置 string strmsg = "GET INFO"; SendMsg2(strmsg, 1); } private void btnsetdk_Click(object sender, EventArgs e) { //设置连接主机端口 string strmsg = "SET IP PORT ";//300 strmsg = strmsg txtdk.Text.Trim(); SendMsg2(strmsg, 1); } private void btnsetid_Click(object sender, EventArgs e) { txtdata.Text = ""; //手动设置地址写入 string str = txtsetid.Text.Trim(); if (str.Length == 14) { str = "6811" str; string idw = string.Empty; // "00 20 19 00 00 00 01 "; string jyhw = "00"; //D1 string[] idstrs = idsplits(str, 2); //3组到20组累加取余,结果给21组 UInt64 sn = 0; for (int k = 0; k < idstrs.Length; k ) { sn = sn Convert.ToUInt64(idstrs[k], 16); } int m = Convert.ToInt32(sn); jyhw = Convert.ToString(m, 16); if (jyhw.Length > 2) { jyhw = jyhw.Substring(1); } else if (jyhw.Length < 2) { jyhw = "0" jyhw; } idw = string.Join(" ", idstrs); string strmsg = "FE FE FE FE " idw " " jyhw " 16"; txtzl.Text = strmsg; SendMsg2(strmsg, 0); } } private void button4_Click(object sender, EventArgs e) { txtdata.Text = ""; } }}
评论